/*!
 * gulp
 * $ npm install gulp-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache --save-dev
 */
// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    gutil = require("gulp-util"),
    async = require("async"),
    del = require('del'),
    env = (process.env.NODE_ENV || "dev"),
    extend = require('./src/js/common/extend');
// Styles
gulp.task('scss', function () {
    return gulp.src('src/scss/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('dist/css/'));
});

var webpack = require("webpack");
var webpackConfig = require("./webpack.config.js"), webpackConfigArray = [];
for (var i = 0; i < webpackConfig.length; i++) {
    webpackConfigArray.push((function (config) {
        return function run(callback) {
            webpack(Object.create(config), function (err, stats) {
                if (err) {
                    gutil.log("[webpack]", err);
                }
                callback(err, true);
            });
        }
    })(webpackConfig[i]))
}
gulp.task("webpack", function (callback) {
    async.series(webpackConfigArray, function (err) {
        callback();
    })
});
gulp.task('common', function () {
    gulp.src('src/fonts/*.*').pipe(gulp.dest('dist/fonts/'));
    gulp.src('src/js/common/**/*.js').pipe(gulp.dest('dist/js/common/'));
    //gulp.src('src/stylesheets/common/**/').pipe(gulp.dest('dist/css/common/'));
});
// Images
gulp.task('images', function () {
    gulp.src('src/images/**/*.*')
        .pipe(gulp.dest('dist/images'));
});
gulp.task('rename', function () {
    gutil.replaceExtension('src/view/**/*.html', '.ejs');
});

// Default task
gulp.task('default', function () {
    gulp.start('scss', 'common', 'images', 'webpack');
    //gulp.start('common','images','webpack');
});
// Watch
gulp.task('watch', function () {
    gulp.start('default');
    // Watch .scss files
    gulp.watch(['src/js/common/*.js'], ['common']);
    gulp.watch(['src/scss/**/*.scss', 'src/scss/*.scss'], ['scss']);

    gulp.watch(['src/images/*.*'], ['images']);
    gulp.watch(['src/js/**/*.js', 'src/view/**/*.ejs'], ['webpack']);
    livereload.listen();
});
